package org.df.ulab.bot.util.core;

import org.df.ulab.bot.api.communication.CommunicationService;
import org.df.ulab.bot.api.core.Engine;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
public final class EngineSession {

	private static final ThreadLocal<CommunicationService> cServices;
	private static final ThreadLocal<Engine> engineCore;
	private static final ThreadLocal<Boolean> keepAlive;
	
	static {
		cServices = new InheritableThreadLocal<CommunicationService>();
		engineCore = new InheritableThreadLocal<Engine>();
		keepAlive = new InheritableThreadLocal<Boolean>();
	}
	
	public static CommunicationService getCommunicationService() {
		return cServices.get();
	}
	
	public static void setCommunicationService(CommunicationService service) {
		if (cServices.get() == null)
			cServices.set(service);
		else
			throw new IllegalStateException("Can not set twice");
	}
	
	public static Engine getEngine() {
		return engineCore.get();
	}
	
	public static void setEngine(Engine engine) {
		keepAlive.set(Boolean.TRUE);
		
		if (engineCore.get() == null) {
			engineCore.set(engine);
		} else
			throw new IllegalStateException("Can not set twice");
	}
	
	public static boolean isAlive() {
		return keepAlive.get();
	}
	
	public static void sessionShutdown() {
		keepAlive.set(Boolean.FALSE);
	}
}
